package client.comm.baoding.ui

import android.Manifest
import android.annotation.SuppressLint
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.view.KeyEvent
import android.webkit.JavascriptInterface
import android.webkit.PermissionRequest
import android.widget.LinearLayout
import androidx.core.content.ContextCompat
import client.comm.baoding.BaseMiddleActivity
import client.comm.baoding.R
import client.comm.baoding.api.bean.UserInfo
import client.comm.baoding.databinding.ActivityNewwebBinding
import client.comm.baoding.ui.viewmodel.MiddleVm
import client.comm.commlib.toast.toast
import client.comm.commlib.utils.SharedUtil
import client.comm.commlib.utils.StoreUtil
import com.google.gson.Gson
import com.just.agentweb.AgentWeb
import com.just.agentweb.DefaultWebClient
import pub.devrel.easypermissions.AppSettingsDialog
import pub.devrel.easypermissions.EasyPermissions


class WebActivity : BaseMiddleActivity<MiddleVm, ActivityNewwebBinding>() {

    override fun getLayout(): Int {
        return R.layout.activity_newweb
    }

    var title: String? = ""
    var url: String? = ""
    var request: PermissionRequest? = null
    protected var mAgentWeb: AgentWeb? = null

    override fun initViewModel(): MiddleVm = createViewModel()

    override fun initView() {
        binding.event = this
        url = intent.getStringExtra("adInfo")
        title = intent.getStringExtra("title")
        binding.title = (title)


        mAgentWeb = AgentWeb.with(this)
            .setAgentWebParent(binding.container, LinearLayout.LayoutParams(-1, -1))
            .useDefaultIndicator()
            .setWebChromeClient(object : com.just.agentweb.WebChromeClient() {
                override fun onPermissionRequest(request: PermissionRequest?) {
                    request?.let {
                        when {
                            it.resources.size > 0 && it.resources.contains("android.webkit.resource.VIDEO_CAPTURE") -> {

                                if (EasyPermissions.hasPermissions(
                                        this@WebActivity,
                                        android.Manifest.permission.CAMERA
                                    )
                                ) {
                                    request.grant(request.resources)
                                    request.getOrigin();
                                } else {


                                    if (EasyPermissions.somePermissionDenied(
                                            this@WebActivity,
                                            Manifest.permission.CAMERA
                                        )
                                    ) {
                                        AppSettingsDialog.Builder(this@WebActivity)
                                            .setTitle("请开启相机权限")
                                            .setRationale("跳转设置界面")
                                            .setRequestCode(0x999)
                                            .build()
                                            .show()
                                    } else {
                                        EasyPermissions.requestPermissions(
                                            this@WebActivity,
                                            "请开启相机权限",
                                            0x999,
                                            android.Manifest.permission.CAMERA
                                        )
                                    }
                                    this@WebActivity.request = it
                                }
                            }

                            it.resources.size > 0 && it.resources.contains("android.webkit.resource.AUDIO_CAPTURE") -> {
                                if (EasyPermissions.hasPermissions(
                                        this@WebActivity,
                                        android.Manifest.permission.RECORD_AUDIO
                                    )
                                ) {
                                    request.grant(request.resources)
                                    request.getOrigin();
                                } else {

                                    if (EasyPermissions.somePermissionDenied(
                                            this@WebActivity,
                                            Manifest.permission.RECORD_AUDIO
                                        )
                                    ) {
                                        AppSettingsDialog.Builder(this@WebActivity)
                                            .setTitle("请开启录音权限")
                                            .setRationale("跳转设置界面")
                                            .setRequestCode(0x990)
                                            .build()
                                            .show()
                                    } else {
                                        EasyPermissions.requestPermissions(
                                            this@WebActivity,
                                            "请开启录音权限",
                                            0x990,
                                            android.Manifest.permission.RECORD_AUDIO
                                        )
                                    }

                                    this@WebActivity.request = it
                                }
                            }

                            else -> {}

                        }
                    }
                }
            })
//            .setWebViewClient(mWebViewClient)
            .setSecurityType(AgentWeb.SecurityType.STRICT_CHECK)
//            .setWebLayout(WebLayout(this))
            .setOpenOtherPageWays(DefaultWebClient.OpenOtherPageWays.ASK) //打开其他应用时，弹窗咨询用户是否前往其他应用
            .interceptUnkownUrl() //拦截找不到相关页面的Scheme
            .createAgentWeb()
            .ready()
            .go(url)
        setFun()
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        return if (mAgentWeb!!.handleKeyEvent(keyCode, event)) {
            true
        } else super.onKeyDown(keyCode, event)
    }

    @SuppressLint("JavascriptInterface")
    fun setFun() {
        mAgentWeb!!.webCreator.webView.addJavascriptInterface(this, "android")
    }

    @JavascriptInterface
    fun backCall() {
        finish()
    }

    @JavascriptInterface
    fun getAppToken(): String {
        return SharedUtil.read("token", "") as String
    }

    @JavascriptInterface
    fun backFinish() {
        finish()
    }

    @JavascriptInterface
    fun getUser(): String? {
        val u = StoreUtil.getBean<UserInfo>(this)
        return Gson().toJson(u)
    }

    override fun onPause() {
        mAgentWeb!!.webLifeCycle.onPause()
        super.onPause()
    }

    override fun onResume() {
        mAgentWeb!!.webLifeCycle.onResume()
        super.onResume()
    }

    override fun onDestroy() {
        //mAgentWeb.destroy();
        mAgentWeb!!.webLifeCycle.onDestroy()
        super.onDestroy()
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
//        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults)
        when (requestCode) {
            0x999 -> {


                if (EasyPermissions.hasPermissions(
                        this@WebActivity,
                        android.Manifest.permission.CAMERA
                    )
                ) {
                    request?.grant(request?.resources)
                    request?.getOrigin();
                    request = null
                } else {

                    AppSettingsDialog.Builder(this@WebActivity)
                        .setTitle("请开启相机权限")
                        .setRationale("跳转设置界面")
                        .setRequestCode(0x999)
                        .build()
                        .show()
//                    toast("获取权限失败")
                }

            }

            0x990 -> {
                if (EasyPermissions.hasPermissions(
                        this@WebActivity,
                        android.Manifest.permission.RECORD_AUDIO
                    )
                ) {
                    request?.grant(request?.resources)
                    request?.getOrigin();
                    request = null
                } else {

                    AppSettingsDialog.Builder(this@WebActivity)
                        .setTitle("请开启录音权限")
                        .setRequestCode(0x990)
                        .setRationale("跳转设置界面")
                        .build()
                        .show()
                    toast("获取权限失败")
                }

            }
        }


    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        when (requestCode) {
            0x999 -> {
                if (ContextCompat.checkSelfPermission(
                        this@WebActivity,
                        android.Manifest.permission.CAMERA
                    )
                    == PackageManager.PERMISSION_GRANTED
                ) {
                    request?.grant(request?.resources)
                    request?.getOrigin();
                    request = null
                } else {
                    toast("获取权限失败")
                    finish()
                }

            }

            0x990 -> {
                if (ContextCompat.checkSelfPermission(
                        this@WebActivity,
                        android.Manifest.permission.RECORD_AUDIO
                    )
                    == PackageManager.PERMISSION_GRANTED
                ) {
                    request?.grant(request?.resources)
                    request?.getOrigin();
                    request = null
                } else {
                    toast("获取权限失败")
                    finish()
                }

            }
        }
    }


    fun goSys() {

        val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url))
//intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        startActivity(intent)
    }

}